/**
 * 
 */
package cc.rico.tutorial.pubsub;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import cc.rico.tutorial.RabbitMQConnectionUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import lombok.extern.slf4j.Slf4j;

/**
 * @author rico
 *
 */
@Slf4j
public class ReceiveLogs {
	 private static final String EXCHANGE_NAME = "logs";

	/**
	 * @param args
	 * @throws TimeoutException 
	 * @throws IOException 
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
		Connection conn = RabbitMQConnectionUtil.getConnection();
		Channel channel = conn.createChannel();
		channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

		// Actively declare a server-named exclusive, autodelete, non-durable queue.
		String queueName = channel.queueDeclare().getQueue();

		// String queue, String exchange, String routingKey
		channel.queueBind(queueName, EXCHANGE_NAME, "");

		Consumer consumer = new DefaultConsumer(channel) {
			@Override
		      public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
		        String message = new String(body, "UTF-8");
		        log.info("[{}] received message = {}", queueName, message);
		        //channel.basicAck(envelope.getDeliveryTag(), false);
		      }
		};

		// String queue, boolean autoAck, Consumer callback
		channel.basicConsume(queueName, true, consumer);
		
		Thread.sleep(1000 * 10);
		RabbitMQConnectionUtil.close(conn, channel);
	}

}
